package com.gec.teams.wechat.exception;

/**
 * 功能：
 * 作者：YumTea
 * 日期：2024/6/18 9:45
 */

import com.gec.teams.wechat.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@Slf4j
@ControllerAdvice
@RestControllerAdvice //捕获springmvc抛出的异常
public class ExceptionAdvice {
    @ResponseBody   //所有返回的对象，转为json格式 发送给前端
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//请求的响应状态码
    @ExceptionHandler(Exception.class)
    public  R exceptionHandler(Exception e){
        log.error("返回处理异常",e);
        if(e instanceof MethodArgumentNotValidException){//后端校验异常
            MethodArgumentNotValidException exception= (MethodArgumentNotValidException) e;
            BindingResult bindingResult = exception.getBindingResult();
            //判断是否是参数数据校验错误
            if(bindingResult.hasErrors()) {
                HashMap<String, Object> map = new HashMap<>();
                List<FieldError> fieldError = bindingResult.getFieldErrors();
                fieldError.forEach(item ->{
                    String message = item.getDefaultMessage();
                    String field = item.getField();
                    map.put(field,message);
                });
                return R.error(HttpStatus.BAD_REQUEST.value(),"方法有误",map);
            }

        }
        else if(e instanceof TeamsException){//业务异常
            TeamsException exception= (TeamsException) e;
            R error = R.error(exception.getCode(), exception.getMsg());
            return error;
        }
        else if(e instanceof UnauthorizedException){
            return R.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"你不具备授权");
        }
            return R.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"服务器异常");
    }



}
